<script setup>
import {ElMessage} from "element-plus";

import {useStore} from "@/stores/store.js";

import { ref } from 'vue'
import {useRouter} from "vue-router";
import axios from "axios";
const form = ref({
  account: '',
  password: ''
})
const router = useRouter()
const loading = ref(false)
const onSubmit = async () => {

  if (form.value.account !== "" && form.value.password !== "") {
  } else {
    ElMessage.error('登录失败，用户名和密码不能为空')
  }

  const formData = {
    account: form.value.account,
    password: form.value.password
  }
  const url = '/user/login'
  console.log(url)
  loading.value = true
  axios.post(url,
      JSON.stringify(formData)
  ).then(async (res)=>{
    if (res.data.flag) {
      // 1.先把token进行一个存储
      // useStore().TOKEN = res.data.data
      localStorage.setItem('token',res.data.data)
      // const token = useStore().TOKEN
      const token = localStorage.getItem('token')
      // 获取到这个全局信息对象
      // const info = useStore().INFO;
      const url1 = '/user/info/get?token=' + token

      // 成功后发一个请求，把用户的信息进行储存一下
      let res1 = await axios.get(url1)
      await localStorage.setItem('username',res1.data.data.username)
      await localStorage.setItem('account',res1.data.data.account)
      await localStorage.setItem('avatar',res1.data.data.avatar)


      // 我想让程序在这里暂停500ms
      // setTimeout(() => {
        // 执行路由跳转
      router.push('/');
      // }, 600);

      loading.value = false
      ElMessage.success('登录成功，跳转到首页')
    } else {
      loading.value = false
      ElMessage.error(res.data.message)
    }
  })
    .catch(err => {
      loading.value = false
      if (err.data != null) {
        ElMessage.error(err.data)
      } else {
        ElMessage.error('无法连接服务器')
      }
    })


  // 向后端发起请求

}
</script>

<template>
  <el-form v-loading="loading" class="form" style="padding: 40px 50px 50px;" :model="form">
    <div style="width: 180px;text-align: center;border-bottom: 2px solid #FF3F29;
      color: #333;line-height: 30px;font-size: 20px;padding-bottom: 10px;margin: 0 auto 30px;">
      密码登录
    </div>
    <el-form-item>
      <el-input maxlength="11" placeholder="用户名" style="width: 370px;height: 47px" v-model="form.account" />
    </el-form-item>
    <el-form-item>
      <el-input placeholder="密码" style="width: 370px;height: 47px" v-model="form.password" type="password" />
    </el-form-item>
    <el-form-item>
      <el-button class="button" type="danger" @click="onSubmit">登 录</el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped>
.form {
  width: 340px;
  background: white;
  position: absolute;
  left: calc(50vw - 220px);
  top: 25%
}
.button {
  background: linear-gradient(to right bottom,#e96161,#e9b38b);
  width: 100%;
  height: 44px;
  color: white;
  cursor: pointer;
  text-align: center;
  font-size: 18px;
  line-height: 44px;
  outline: none;
}
</style>
